<template>
  <a-modal
    v-model:visible="props.visible"
    title="Schema 代码预览"
    width="800px"
    :footer="null"
  >
    <div class="code-preview">
      <div class="toolbar">
        <a-space>
          <a-button type="primary" size="small" @click="copyCode">
            <template #icon><CopyOutlined /></template>
            复制代码
          </a-button>
          <a-radio-group v-model:value="format" size="small">
            <a-radio-button value="json">JSON</a-radio-button>
            <a-radio-button value="javascript">JavaScript</a-radio-button>
          </a-radio-group>
        </a-space>
      </div>
      <a-alert
        v-if="copied"
        message="代码已复制到剪贴板"
        type="success"
        show-icon
        class="copy-alert"
      />
      <pre class="code-block"><code>{{ formattedCode }}</code></pre>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { CopyOutlined } from '@ant-design/icons-vue';
import { useEditorStore } from '@/stores/editor';

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
}>();

const editorStore = useEditorStore();
const format = ref<'json' | 'javascript'>('json');
const copied = ref(false);

const generateSchema = () => {
  const components = editorStore.canvasComponents;
  return {
    type: 'object',
    properties: components.reduce((acc, component) => {
      acc[component.id] = {
        ...component.configData.config,
        style: component.style,
        events: component.events,
      };
      return acc;
    }, {}),
  };
};

const formattedCode = computed(() => {
  const schema = generateSchema();
  if (format.value === 'json') {
    return JSON.stringify(schema, null, 2);
  } else {
    return `export default ${JSON.stringify(schema, null, 2)}`;
  }
});

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(formattedCode.value);
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 3000);
  } catch (err) {
    console.error('Failed to copy code:', err);
  }
};
</script>

<style lang="less" scoped>
.code-preview {
  position: relative;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.copy-alert {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 1;
}

.code-block {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  max-height: 600px;
  overflow: auto;
  margin: 0;
  font-family: 'Fira Code', 'Consolas', monospace;
  font-size: 14px;
  line-height: 1.5;
  
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 4px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f5f5f5;
  }
}
</style> 